package com.xhs.websocket;

import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

/**
 * @desc: 监听连接的建立关闭、消息接收 处理类
 * @projectName: spring-boot-websocket
 * @author: xhs
 * @date: 2025-03-24 周一 23:18
 * @version: JDK 1.8
 */
@Slf4j
@Component
@EqualsAndHashCode
@ServerEndpoint("/websocket/{username}")
public class WebSocketServer {

    /**
     * WebSocket 连接成功建立时触发
     *
     * @param username username
     * @param session  session
     */
    @OnOpen
    public void openSession(@PathParam("username") String username, Session session) {
        log.info("WebSocket 连接成功建立！username：{}，session：{}", username, session.getId());
    }

    /**
     * 当服务器接收到客户端发送的消息时触发
     *
     * @param username username
     * @param message  message
     */
    @OnMessage
    public void onMessage(@PathParam("username") String username, String message) {
        log.info("服务器接收到客户端发送的消息！username：{}，message：{}", username, message);
    }

    /**
     * 当 WebSocket 连接关闭时触发
     *
     * @param username username
     * @param session  session
     */
    @OnClose
    public void onClose(@PathParam("username") String username, Session session) {
        log.info("WebSocket 连接关闭！username：{}，session：{}", username, session.getId());
    }

    /**
     * 当 WebSocket 连接过程中发生错误时触发
     *
     * @param session  session
     * @param username username
     * @param error    入参
     */
    @OnError
    public void onError(Session session, @PathParam(value = "username") String username, Throwable error) {
        log.error("WebSocket发生错误-用户标识:{}, 会话ID:{}, 错误信息:{}", username, session.getId(), error.getMessage());
    }

}
